/*******************************************************************************
 * 版权：北京润尼尔网络科技有限公司，保留所有版权<br>
 * 版本：v1.0.0<br>
 * 文件：CommandCopy.js<br>
 * 日期：2018年8月31日<br>
 * 作者: 孙燕宝<br>
 * 功能：添加主题命令<br>
 *
 * 修改记录：<br>
 * 日期 描述 更新功能<br>
 ******************************************************************************/

window.makeNamespace(window, 'Rainier.UI.V2');

/**
 * 类型名称：Rainier.UI.V2.CommandAddTheme<br>
 * 类型功能：添加主题命令<br>
 */
Rainier.UI.V2.CommandAddTheme = draw2d.command.Command.extend({
  NAME: 'Rainier.UI.V2.CommandAddTheme',

  /**
   * 函数名称：Rainier.UI.V2.CommandAddTheme.init<br>
   * 函数功能：构造函数<br>
   * 异常信息：无<br>
   */
  init: function (context, editParts) {
    this.context = context;
    this.editPart = editParts.data[0];
    this.rootEditPart = this.context.getRootEditPart();
    this.addInfo = {};
    this.deleteInfo = {};
    this.tabId = app.canvasId;
    this.activeEditor = app.getContext().getActiveEditor();
    this._super();
  },

  /**
   * 函数名称：Rainier.UI.V2.CommandAddTheme.execute<br>
   * 函数功能：执行命令<br>
   * 函数返回：无<br>
   * 异常信息：无<br>
   */
  execute: function () {
    //控制添加树结构形式
    treeControl = true;
    if (!this.editPart) {
      return;
    }
    var _this = this;
    var model = this.editPart.getModel();
    //选中主题的位置和属性
    var property = model.property;
    var modelProperty = property.modelProperty;
    var uiProperty = property.uiProperty;
    var parentX = uiProperty.x;
    var parentY = uiProperty.y;
    //添加主题json
    var json = null;
    if (modelProperty.typeName == 'TextModelJson') {
      json = Rainier.UI.V2.Communication.TextModelJson;
    }
    if (modelProperty.typeName == 'TextModelOval') {
      json = Rainier.UI.V2.Communication.TextModelOval;
    }
    if (modelProperty.typeName == 'TextModelDiamond') {
      json = Rainier.UI.V2.Communication.TextModelDiamond;
    }
    // else if(modelProperty.typeName=='TextModelJson2'){
    // 	json = Rainier.UI.V2.Communication.TextModelJson3;
    // }
    // else if(modelProperty.typeName=='TextModelJson3'){
    // 	// OverThreeTextModelJson不会出现在器材栏
    // 	json = Rainier.UI.V2.Communication.OverThreeTextModelJson;
    // }
    // else if(modelProperty.typeName=='OverThreeTextModelJson'){
    // 	// OverThreeTextModelJson不会出现在器材栏
    // 	json = Rainier.UI.V2.Communication.OverThreeTextModelJson;
    // }

    //颜色渐变
    var colorArr = [
      '#003238',
      '#004C56',
      '#00606C',
      '#00707E',
      '#007E8D',
      '#008999',
      '#0099AB',
      '#02A8BC',
      '#02BDD2',
      '#00C7DF',
      '#02D5ED',
      '#00E5FF',
      '#26E9FF',
      '#46EDFF',
      '#65EFFF',
    ];
    var bgColor = null;
    if (uiProperty.bgColor) {
      bgColor = uiProperty.bgColor;
      var index = colorArr.indexOf(bgColor);
      if (colorArr[index + 1]) {
        bgColor = colorArr[index + 1];
      } else {
        bgColor = bgColor;
      }
    }

    // json.uiProperty.color =
    json.uiProperty.bgColor = bgColor;
    //仿照CommandDelete的undo
    var createdModel = this.deleteInfo.model;
    if (createdModel) {
      var portList = this.deleteInfo.ports.clone();
      portList.each(function (index, port) {
        createdModel.addPort(port);
      });
    } else {
      createdModel = Rainier.UI.V2.DeviceModelBuilder.buildModel(json);
    }

    //添加器件id
    if (!createdModel.property.modelProperty.id) {
      createdModel.property.modelProperty.id = new Date().getTime();
    }
    // 修改器件label
    var typeName = createdModel.property.modelProperty.typeName;
    if (typeName === 'TextModelJson' || typeName === 'TextModelOval' || typeName === 'TextModelDiamond') {
      createdModel.property.modelProperty.defaultLabel = modelProperty.label + '.';
    }

    var newChildX = null;
    var newChildY = null;
    var parentPorts = [];
    var childPorts = [];
    var sPort = null;
    var tPort = null;
    var inputs = model.getInputPorts();
    var outputs = model.getOutputPorts();
    var hybrids = model.getHybridPorts();

    inputs.each(function (i, p) {
      parentPorts.push(p);
    });
    outputs.each(function (i, p) {
      parentPorts.push(p);
    });
    hybrids.each(function (i, p) {
      parentPorts.push(p);
    });
    $.each(parentPorts, function (index, port) {
      if (port.property.modelProperty.locator.defaultY == uiProperty.height) {
        sPort = port;
      }
    });
    if (modelProperty.children.length == 0) {
      newChildX = parentX + (1 / 2) * uiProperty.width - createdModel.property.uiProperty.width / 2;
      newChildY = parentY + uiProperty.height + createdModel.property.uiProperty.width / 3;

      if (createdModel) {
        var inputs = createdModel.getInputPorts();
        var outputs = createdModel.getOutputPorts();
        var hybrids = createdModel.getHybridPorts();

        inputs.each(function (i, p) {
          childPorts.push(p);
        });
        outputs.each(function (i, p) {
          childPorts.push(p);
        });
        hybrids.each(function (i, p) {
          childPorts.push(p);
        });
      }
      //添加新孩子
      var parentModel = this.editPart.getParent().getModel();
      parentModel.addChildModel(createdModel);
      createdModel.setPosition(newChildX, newChildY, false);
      //添加连线
      var connection = Rainier.UI.V2.Communication.ConnectionModel[1];
      connection.uuid = new Date().getTime();
      connection.modelProperty.direction = 'vertical';
      for (var i = 0; i < childPorts.length; i++) {
        var port = childPorts[i];
        if (port.property.modelProperty.locator.defaultY == 0) {
          tPort = port;
          if (sPort) {
            _this.activeEditor.makeConnection(sPort, tPort, connection);
          }
        }
      }
    } else {
      //新孩子右移
      var children = modelProperty.children;
      // var model = this.getModelById(children[children.length-1]);
      var searchedModel = this.getModelById(children[children.length - 1]);
      if (searchedModel === null) {
        searchedModel = this._getModelById(children[children.length - 1]);
      }
      var sTypeName = searchedModel.property.modelProperty.typeName;
      if (sTypeName === 'TextModelJson' || sTypeName === 'TextModelOval' || sTypeName === 'TextModelDiamond') {
        if (searchedModel.property.uiProperty.width <= 180) {
          newChildX =
            searchedModel.property.uiProperty.x + searchedModel.property.uiProperty.width / 2 + 117 - 136 + 64;
        } else {
          newChildX = searchedModel.property.uiProperty.x + searchedModel.property.uiProperty.width - 136 + 64;
        }
      } else {
        newChildX = searchedModel.property.uiProperty.x;
      }

      newChildY = searchedModel.property.uiProperty.y;
      //老孩子左移
      this.moveLeftTree(model, 'left');
      this.moveRightTree(model, 'right');
      this.moveChildren(children, 'left');
      if (createdModel) {
        var inputs = createdModel.getInputPorts();
        var outputs = createdModel.getOutputPorts();
        var hybrids = createdModel.getHybridPorts();
        //清空老孩子ports
        childPorts = [];

        inputs.each(function (i, p) {
          childPorts.push(p);
        });
        outputs.each(function (i, p) {
          childPorts.push(p);
        });
        hybrids.each(function (i, p) {
          childPorts.push(p);
        });
      }
      //添加新孩子
      var parentModel = this.editPart.getParent().getModel();
      parentModel.addChildModel(createdModel);
      createdModel.setPosition(newChildX, newChildY, false);
      //添加连线
      var connection = Rainier.UI.V2.Communication.ConnectionModel[0];
      connection.uuid = new Date().getTime();
      connection.modelProperty.direction = 'vertical';
      $.each(childPorts, function (index, port) {
        if (port.property.modelProperty.locator.defaultY == 0) {
          tPort = port;
          if (sPort) {
            var segment = connection.modelProperty.segments;
            //终点x
            var x = createdModel.property.uiProperty.x;
            segment[1].start_x = x + createdModel.property.uiProperty.width / 2;
            segment[1].start_y = parentY + uiProperty.height;
            _this.activeEditor.makeConnection(sPort, tPort, connection);
          }
        }
      });
    }

    //判断器材展示栏中是否已存在该器材，若存在则不再再次向展示栏中添加
    var className = createdModel.property.modelProperty.typeName;
    var componentName = createdModel.property.modelProperty.componentName;
    this.addUsedPart(className, componentName);
    // console.log(data);

    this.addInfo.createdModel = createdModel;
    // this.refreshConnection();

    //添加孩子信息
    var _id = createdModel.property.modelProperty.id;
    modelProperty.children.push(_id);
    //添加父主题信息
    createdModel.property.modelProperty.parent = property.modelProperty.id;

    var txt = createdModel.property.modelProperty.label.replace(/-/g, '.');

    //添加主题后,树结构同步
    var parentId = modelProperty.id;
    var nodeParent = $('#ul-mindMap').tree('find', parentId);
    if (!nodeParent) {
      var _nodeParent = $('#ul-mindMap').tree('find', 'firstPage');
      var _txt = modelProperty.label.replace(/-/g, '.');
      $('#ul-mindMap').tree('append', {
        parent: _nodeParent.target,
        data: [
          {
            id: parentId,
            text: _txt + ' ' + modelProperty.text,
            state: 'open',
            animate: true,
          },
        ],
      });
      nodeParent = $('#ul-mindMap').tree('find', parentId);
    }
    $('#ul-mindMap').tree('append', {
      parent: nodeParent.target,
      data: [
        {
          id: createdModel.property.modelProperty.id,
          text: txt + ' ' + createdModel.property.modelProperty.text,
          state: 'open',
          animate: true,
        },
      ],
    });
    treeControl = false;

    //更新预览图
    // if(isSelectedPreview){
    // 	var delay = setTimeout(function(){
    // 		var img = $("#img-preview");
    // 		refreshPreview(img);
    // 	},1000);
    // 	if(delay){
    // 		clearTimeout(delay);
    // 	}
    // }
  },

  /**
   * 函数名称：Rainier.UI.V2.CommandAddTheme.getModelById<br>
   * 函数功能：根据主题id查询对应model<br>
   * 参数输入：无<br>
   * 参数输出：无<br>
   * 函数返回：无<br>
   * 异常信息：无<br>
   */
  getModelById: function (id) {
    var parentModel = this.editPart.getParent().getModel();
    var children = parentModel.m_aChildren;
    var model = null;
    if (children) {
      $.each(children, function (index, child) {
        var _id = child.property.modelProperty.id;
        if (_id == id) {
          model = child;
        }
      });
    }
    return model;
  },

  /**
   * 函数名称：Rainier.UI.V2.CommandAddTheme._getModelById<br>
   * 函数功能：根据主题id在已经隐藏图片库查询对应model<br>
   * 参数输入：无<br>
   * 参数输出：无<br>
   * 函数返回：无<br>
   * 异常信息：无<br>
   */
  _getModelById: function (id) {
    var model = null;
    var hideArr = hideImgArr[this.tabId];
    if (hideArr) {
      if (hideArr.length > 0) {
        $.each(hideArr, function (index, deleteInfo) {
          var _id = deleteInfo.model.property.modelProperty.id;
          if (_id == id) {
            model = deleteInfo.model;
          }
        });
      }
    }
    return model;
  },

  /**
   * 函数名称：Rainier.UI.V2.CommandAddTheme.moveLeftTree<br>
   * 函数功能：新建主题用的递归函数<br>
   * 参数输入：无<br>
   * 参数输出：无<br>
   * 函数返回：无<br>
   * 异常信息：无<br>
   */
  moveLeftTree: function (model, direction) {
    var parent = model.property.modelProperty.parent;
    if (parent) {
      var parentModel = this.getModelById(parent);
      var children = parentModel.property.modelProperty.children;
      var modelId = model.property.modelProperty.id;
      var index = children.indexOf(modelId);
      var childrenLeft = children.slice(0, index);
      this.moveChildren(childrenLeft, direction);
      this.moveLeftTree(parentModel, direction);
    }
  },

  /**
   * 函数名称：Rainier.UI.V2.CommandAddTheme.moveRightTree<br>
   * 函数功能：新建主题用的递归函数<br>
   * 参数输入：无<br>
   * 参数输出：无<br>
   * 函数返回：无<br>
   * 异常信息：无<br>
   */
  moveRightTree: function (model, direction) {
    var parent = model.property.modelProperty.parent;
    if (parent) {
      var parentModel = this.getModelById(parent);
      var children = parentModel.property.modelProperty.children;
      var modelId = model.property.modelProperty.id;
      var index = children.indexOf(modelId);
      var childrenRight = children.slice(index + 1);
      this.moveChildren(childrenRight, direction);
      this.moveRightTree(parentModel, direction);
    }
  },

  /**
   * 函数名称：Rainier.UI.V2.CommandAddTheme.moveChildren<br>
   * 函数功能：新建主题用的递归函数<br>
   * 参数输入：无<br>
   * 参数输出：无<br>
   * 函数返回：无<br>
   * 异常信息：无<br>
   */
  moveChildren: function (children, direction) {
    var _this = this;
    for (var i = 0; i < children.length; i++) {
      var _id = children[i];
      var childModel = this.getModelById(_id);
      if (childModel === null) {
        childModel = this._getModelById(_id);
      }
      var uiProperty = childModel.property.uiProperty;
      var x = uiProperty.x;
      var y = uiProperty.y;
      var oldChildX = null;
      if (direction == 'left') {
        oldChildX = x - 136;
      }
      if (direction == 'right') {
        oldChildX = x + 136;
      }
      var oldChildY = y;
      //更新老孩子位置
      childModel.setPosition(oldChildX, oldChildY, false);
      var _children = childModel.property.modelProperty.children;
      if (direction == 'left') {
        if (_children) {
          _this.moveChildren(_children, 'left');
        }
      }
      if (direction == 'right') {
        if (_children) {
          _this.moveChildren(_children, 'right');
        }
      }
    }
  },

  /**
   * 函数名称：Rainier.UI.V2.CommandAddTheme.refreshConnection<br>
   * 函数功能：重新绘制连线<br>
   * 参数输入：无<br>
   * 参数输出：无<br>
   * 函数返回：无<br>
   * 异常信息：无<br>
   */
  refreshConnection: function () {
    //删除错误连线
    //遍历三次，否则不能删除干净
    var connections = this.activeEditor.rootModel.connections.data;
    var _connection = Rainier.UI.V2.Communication.ConnectionModel[0];

    for (var j = 0; j < 3; j++) {
      connections = this.activeEditor.rootModel.connections.data;
      for (var i = 0; i < connections.length; i++) {
        var connection = connections[i];
        // 只刷新竖向连线
        if (
          connection.property.modelProperty.direction !== 'undefined' &&
          connection.property.modelProperty.direction == 'vertical'
        ) {
          var segments = connection.property.modelProperty.segments;
          if (segments.length > 1) {
            if (segments[0].type == 'vertical' || segments[1].type == 'horizontal') {
              //确保新线完成再删除错误
              var complete = false;
              //确保id相同
              _connection.uuid = connection.m_sUuid;
              //删除连线
              var sourcePort = connection.sourcePort;
              var targetPort = connection.targetPort;
              var _segment = connection.property.modelProperty.segments;
              var x = _segment[1].end_x;
              var y = _segment[0].start_y;
              if (sourcePort) {
                var segment = _connection.modelProperty.segments;
                segment[1].start_x = x;
                segment[1].start_y = y;
                this.activeEditor.makeConnection(sourcePort, targetPort, _connection);
              }
              complete = true;
              if (complete) {
                this.rootEditPart.getModel().removeConnection(connection);
              }
            }
          }
        }
      }
    }
  },

  /**
   * 函数名称：Rainier.UI.V2.CommandAddTheme.undo<br>
   * 函数功能：撤销命令<br>
   * 函数返回：无<br>
   * 异常信息：无<br>
   */
  undo: function () {
    //移除新添加的主题
    var model = this.addInfo.createdModel;
    var parentModel = this.editPart.getParent().getModel();

    // 删除已添加到已使用器材的器件
    var className = model.property.modelProperty.typeName;
    this.deleteUsedPart(className);

    this.deleteInfo = parentModel.removeChildModel(model);
    //同步删除树结构
    var id = model.property.modelProperty.id;
    var node = $('#ul-mindMap').tree('find', id);
    if (node) {
      $('#ul-mindMap').tree('remove', node.target);
    }
    //父节点删除子信息
    var parentId = model.property.modelProperty.parent;
    var parent = this.getModelById(parentId);
    if (parent) {
      var children = parent.property.modelProperty.children;
      var _children = [];
      for (var i = 0; i < children.length; i++) {
        var _id = children[i];
        if (_id == id) {
          var index = children.indexOf(_id);
          children.splice(index, 1);
        } else {
          _children.push(_id);
        }
      }
      //老孩子移动到原位
      this.moveChildren(_children, 'right');
      if (children.length > 0) {
        this.moveLeftTree(parent, 'right');
        this.moveRightTree(parent, 'left');
      }
    }
    this.refreshConnection();
  },

  /**
   * 函数名称：Rainier.UI.V2.CommandAddTheme.redo<br>
   * 函数功能：重做命令<br>
   * 函数返回：无<br>
   * 异常信息：无<br>
   */
  redo: function () {
    this.execute();
  },

  /**
   * 函数名称：Rainier.UI.V2.CommandAddTheme.addUsedPart<br>
   * 函数功能：(单个添加器件)判断器材展示栏中是否已存在该器材，若存在则不再再次向展示栏中添加<br>
   * 函数输入：className和componentName
   * 函数返回：无<br>
   * 异常信息：无<br>
   */
  addUsedPart: function (className, componentName) {
    var usedPart = {};
    usedPart.isLogic = true;
    usedPart.courseType = 'Communication';
    usedPart.deviceType = 'PmsModel';
    //data_part:data的一个对象
    var data_part = {};
    data_part.className = className;
    // 还未向实验台添加器件时
    if (data.length == 0) {
      if (className) {
        data_part.addCount = 1;
      }
      data.push(data_part);
      usedPart.className = data[0].className;
      usedPart.componentName = componentName;
      usedPartArray.push(usedPart);
      // 实验台上已经存在器件时
    } else {
      for (var i = 0; i < data.length; i++) {
        if (data[i].className == className) {
          // console.log("已加入已使用器件数组!");
          data[i].addCount += 1;
          return;
        }
      }
      data_part.addCount = 1;
      data.push(data_part);
      usedPart.className = data[data.length - 1].className;
      usedPart.componentName = componentName;
      usedPartArray.push(usedPart);
    }
  },

  /**
   * 函数名称：Rainier.UI.V2.CommandAdd.deleteUsedPart<br>
   * 函数功能：根据addCount的值删除器件展示栏中的器件，若为0，则删除<br>
   * 函数返回：无<br>
   * 异常信息：无<br>
   */
  deleteUsedPart: function (className) {
    if (className) {
      for (var i = 0; i < data.length; i++) {
        if (className == data[i].className) {
          data[i].addCount -= 1;
          if (data[i].addCount > 0) {
            // console.log("实验台上还存在"+className);
            return;
          } else {
            data.splice(i, 1);
            // addCount<=0且usedPartArray中存在该className对应的器件信息时，将该器件从器件展示栏删除
            for (var j = 0; j < usedPartArray.length; j++) {
              if (usedPartArray[j].className == className) {
                usedPartArray.splice(j, 1);
              }
            }
          }
        }
      }
    }
  },
});
var treeControl = false;
